package com.alisonyu.spider.Router;

import com.alisonyu.spider.Proccessor.Context;

import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 路由对象
 * Created by yu on 2017/9/23.
 */
public class Route implements RouteInterface,Regex{
    //正则匹配条件
    private String regex;
    //可选择的URL进一步条件匹配
    private Predicate urlFilter;
    //对内容进行过滤匹配
    private Predicate<String> contentFilter;
    //应用函数
    private Consumer<Context> consumer;

    public Route(){
        this.urlFilter=(url->true);
        this.consumer=(html -> {});
    }


    @Override
    public RouteInterface regex(String regex) {
        this.regex=regex;
        return this;
    }

    @Override
    public RouteHandler contentFilter(Predicate<String> predicate) {
        return null;
    }

    @Override
    public RouteHandler filter(Predicate<String> predicate){
        this.urlFilter=predicate;
        return this;
    }

    @Override
    public Consumer handler(Consumer<Context> consumer){
        this.consumer=consumer;
        return this.consumer;
    }

    public void handle(Context html){
        this.consumer.accept(html);
    }

    public boolean match(String url,String content){
        if(!matchRegex(url)) return false;
        if(!matchFilters(url)) return false;
        if(!matchContentFilter(content)) return false;
        return true;
    }

    private boolean matchRegex(String url){
        if(regex==null) return true;
        return url.matches(regex);
    }

    private boolean matchFilters(String url){
        if(this.urlFilter==null) return true;
        return this.urlFilter.test(url);
    }

    private boolean matchContentFilter(String content){
        if(this.contentFilter==null) return true;
        return this.contentFilter.test(content);
    }



}